<template>
  <div class="mainBox">
      <div class="container">
        <el-row :gutter="20">
          <el-col :span="18">
            <span>用户组</span>
            <el-select v-model="searchParam.group_id" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in userGroupsArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <span>状态</span>
            <el-select v-model="searchParam.status" clearable placeholder="请选择">
              <el-option
                v-for="item in userStatusArr"
                :key="item.value"
                :label="item.text"
                :value="item.value">
              </el-option>
            </el-select>
            <span>关键字</span>
            <el-input style="width: 250px;" v-model="searchParam.keyword" clearable @keyup.enter.native="getUsersList" placeholder="请输入用户名关键字"></el-input>
            <el-button type="primary" :loading="loading" @click="getUsersList" size="small" icon="el-icon-search">查询</el-button>
          </el-col>
          <el-col :span="3" >
            <el-button  type="primary" @click="openDialog" size="small" icon="el-icon-plus">添加用户</el-button>
          </el-col>
        </el-row>
      </div>
      <!-- Table -->
      <el-table
        v-loading="loading"
        element-loading-text="拼命加载中..."
        :data="userTableData"
        border
        style="width: 100%">
        <el-table-column
          label="No."
          type="index"
          :index="indexMethod"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          label="用户"
          prop="username"
          align="center"
          width="180"
          >
        </el-table-column>
        <el-table-column
          label="用户组"
          width="280"
          align="center">
            <template slot-scope="scope">
              <span v-for="(item, index) in scope.row.groups">{{ item.name }}/</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="role.display_name"
          label="角色"
          width="180"
          align="center">
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="创建时间"
          width="200"
          align="center">
        </el-table-column>
        <el-table-column
          prop="update_at"
          label="活跃时间"
          align="center"
          width="200">
        </el-table-column>
        <el-table-column
          label="状态"
          align="center"
          width="180"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.status == '1' ? 'success' : 'danger'"
                close-transition>{{scope.row.status | userStatusFilter}}</el-tag>
            </template>
        </el-table-column>
        <el-table-column label="操作"  align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              :type="scope.row.status === 1 ? '':'success'"
              @click="statusHandleEdit(scope.$index, scope.row)">{{scope.row.status === 1 ? '禁用' : '启用'}}</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
             <el-button
              size="mini"
              type="info"
              @click="SeeAllTasks(scope.$index, scope.row)">查看任务</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-show="total" class="pagination-container" style="margin-top: 20px;">
        <el-pagination
            background
            class="pagination-container" style="margin-top: 20px;"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="searchParam.page"
            :page-sizes="[10,20,50,100]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
      </div>

      <!-- dialog 添加用户-->
      <el-dialog title="用户" :visible.sync="dialogFormVisible" @close="closeDialog">
        <el-form :model="form" :rules="rules" ref="addUserForm" label-width="120px" style="">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名称" auto-complete="off" :disabled='operType == 2'></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="operType == 1 || (operType == 2 && (roles.indexOf('admin') != -1 || roles.indexOf('superadmin') != -1) ) ">
            <el-input v-model="form.password" placeholder="请输入密码" auto-complete="off" :maxlength="10"></el-input>
          </el-form-item>
          <el-form-item label="角色"  prop="role_id">
            <el-select v-model="form.role_id" clearable filterable placeholder="请选择">
              <el-option
                v-for="item in rolesArr"
                :key="item.id"
                :label="item.display_name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户组" prop="">
            <el-select v-model="form.group_id_list" clearable filterable multiple placeholder="请选择">
              <el-option
                v-for="item in userGroupsArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              v-model="status_Boolean"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="add_switchChange"
              >
              </el-switch>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('addUserForm')">保存</el-button>
            <el-button @click="resetForm('addUserForm')">重置</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <!--<el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
        </div>
      </el-dialog>
  </div>
</template>


<script>
import {getUserGroup} from '@/api/userGroup'
import {getUsers,addUser,delUser,getRoles,UserDetail,updateUser} from '@/api/users'
import {userStatusArr,userStatusFilter} from '@/utils/static_data'
import { mapGetters } from 'vuex'
export default{
  data() {
    return {
      userStatusArr,
      total:0,
      pageSize: 10,
      dialogFormVisible: false,
      form:{
        username: '',
        password:'',
        group_id_list: [],
        role_id: '',
        status: 1
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        group_id_list: [
          { required: true, message: '请选择用户组', trigger: 'blur' }
        ],
        role_id: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ]
      },
      operType: 1, // 1 add; 2 update
      userId:'',
      status: '1',
      status_Boolean: true,
      searchParam:{
        status: '',
        group_id: '',
        per_page: 10,
        page: 1,
        keyword: ''
      },
      userGroupsArr:[],
      userTableData:[], //用户列表数据
      rolesArr:[] //角色下拉框
      ,loading: true
    }
  },
  created(){
    this.searchParam.group_id = this.$route.params.groupId || ''
    this.getUsersList()
    this.getUserGroupList()
    this.getRolesList()
  },
  methods: {
    //获取用户组下拉框列表
    getUserGroupList(){
      getUserGroup({
        per_page: 1000
      },response=> {
        const res = response.data
        if(res.code == 1){
          this.userGroupsArr = (res.data).items
        }
      })
    },
    //用户列表
    getUsersList(){
      this.loading = true
      getUsers(this.searchParam, response=> {
        const res = response.data
        if(res.code == 1){
          this.userTableData = (res.data).items
          this.total = (res.data).total
          if((res.data).page > (res.data).pages && (res.data).pages !== 0){
            this.searchParam.page = (res.data).pages
            this.getUsersList()
          }
        }
        this.loading = false
      })
     },
    //保存
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
            // console.log('--->>'+ JSON.stringify(this.form))
          this.form.status = this.status_Boolean ? 1 : 0
          if(this.operType == 1){
            this.addUserFun()
          }else{
            this.updateUserFun()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //添加用户
    addUserFun(){
      addUser(this.form, response=> {
        const res = response.data;
        if(res.code == 1){
          this.$message.success('添加成功')
          this.dialogFormVisible = false
          this.getUsersList();
        }
      })
    },
    //更新
    updateUserFun(){
      let json = this.form
      if((this.roles.indexOf('admin') == -1 || this.roles.indexOf('superadmin') == -1) ){
        delete json.password
      }
      updateUser(this.userId, json, response=> {
        const res = response.data;
        if(res.code === 1){
          this.$message.success('更新成功')
          this.getUsersList();
          this.dialogFormVisible = false
        }
      })
    },
    //编辑
    handleEdit(index, row) {
      // console.log(index, row);
      this.userId = row.id
      this.operType = 2
      UserDetail(row.id, response=> {
        const res = response.data;
        if(res.code === 1){
          this.form.username = (res.data).username;
          this.form.password = (res.data).password;
          this.form.group_id_list = [];
          ((res.data).groups).forEach(item=>{
            (this.form.group_id_list).push(item.id)
          })
          this.form.role_id = ((res.data).role).id;
          this.status_Boolean = (res.data.status === 1) ? true : false
          this.dialogFormVisible = true
        }
      })
    },
    //删除
    handleDelete(index, row) {
      this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUser(row.id, response=> {
            if(response.status == 200){
              this.getUsersList()
              this.$message.success('删除成功')
            }
          })
        }).catch(() => {
        });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.searchParam.per_page = val;
      this.getUsersList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.searchParam.page = val;
      this.getUsersList();
    },
    //dialog close
    closeDialog(){
      this.operType = 1;
      this.resetForm('addUserForm')
    },
    openDialog(){
      this.dialogFormVisible = true
    },
     //重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.status_Boolean = true
      this.form.group_id_list = []
      this.form.username = ''
      this.form.password = ''
      this.form.role_id = ''
    },
    //用户状态切换Btn
    statusHandleEdit(index, row){
      this.userId = row.id
      updateUser(this.userId, {
        "status": row.status === 1 ? 0 : 1
      }, response=> {
        const res = response.data;
        if(res.code === 1){
          this.$message.success('切换成功')
          // this.getUsersList();
          this.userTableData[index].update_at = (res.data).update_at
          this.userTableData[index].status = (res.data).status
        }
      })
    },
    //添加Form - switch
    add_switchChange(val){
      this.status_Boolean = val
    },
    //获取角色
    getRolesList(){
      getRoles(response=> {
      const res = response.data
      if(res.code == 1){
        this.rolesArr = res.data;
      }
    })
    },
    //查看所有任务
    SeeAllTasks(index, row){
      const uId = row.id
      this.$router.push({ name: 'tasks_index', params: { uId }})
    },
    indexMethod(index) {
      let No = (this.searchParam.page -1) * this.searchParam.per_page
      return No + (index + 1)
    }
  },
  filters:{
    userStatusFilter(score){
      return userStatusFilter(score)
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .mainBox{
    padding: 0px;
    margin-bottom: 20px;
  }
  .container {
    margin: 10px 0px;
  }
</style>
